<template>
  <a-drawer destroy-on-close width="1100" title="提交线索字段列表" :visible="visible"
            @close="onClose" body-style="height: 100%">

    <div class="box  flex">
      <div class="left flex flex-column  ">
        <div class="open-config" :class="selectIndex==-1?'select-style':''"
             @click="changeProject(-1)">
          <unordered-list-outlined style="color: #2681f3"/>
          公共字段
        </div>
        <a-divider style="margin: 10px 0"/>
        <div class="open-config">
          <home-outlined style="color: #2681f3"/>
          各项目字段
        </div>
        <div class="flex-1" style="overflow:scroll;margin-top: 10px">
          <a-list>
            <a-list-item v-for="(item,index) in villageList">
              <div class="open-config" style="margin-left: 20px"
                   :class="selectIndex==index?'select-style':''"
                   @click="changeProject(index)">
                {{ item.label }}
              </div>
            </a-list-item>
          </a-list>
        </div>
      </div>
      <div class="config">
        <div class="table-config">
          <a-table class="" :columns="columns" :data-source="tableList"
                   :pagination="false" bordered>
            <template #title>
              <div class="flex space-between align-center">
                <div class="flex-1">
                  <a-form layout="inline" ref="searchFormRef" :model="modelRef">
                    <a-form-item name="field_name">
                      <a-input style="width: 160px" placeholder="请输入字段名称"
                               v-model:value="modelRef.field_name"/>
                    </a-form-item>
                    <a-space>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="toSearch">搜索</a-button>
                    </a-space>
                  </a-form>

                </div>
                <a-space v-if="selectIndex!=-1">
                  <a-checkbox :checked="showPublic" @change="changePublic">显示公共字段
                  </a-checkbox>
                  <a-button type="primary" @click="addItem">添加字段</a-button>
                </a-space>
              </div>
            </template>
            <template #bodyCell="{column,record}">
              <template v-if="column.key=='field_type'">
                <span v-if="record.field_type=='input'">单行文本框</span>
                <span v-else-if="record.field_type=='textarea'">多行文本框</span>
                <span
                    v-else-if="record.field_type=='singleSelect'||record.field_type=='select'">单选下拉框</span>
                <span v-else-if="record.field_type=='mutiSelect'">多选下拉框</span>
                <span v-else-if="record.field_type=='image'">图片</span>
                <span v-else-if="record.field_type=='file'">附件</span>

              </template>
              <template v-if="column.key=='projectName'">
                {{ projectName }}
              </template>

              <template v-if="column.key=='is_required'">
                {{ record.is_required == 1 ? "是" : "否" }}
              </template>
              <template v-if="column.key=='sort'">
                <template v-if="record.alias=='village_id'">
                  置顶
                </template>
                <template v-else>
                  <a-input-number min="1" max="100"
                                  v-model:value="record.sort"
                                  @change="(e)=>changeSort(record,e)"></a-input-number>
                </template>
              </template>
              <template v-if="column.key=='action'">
                <a-button type="link" @click="editItem(record)" :disabled="record.is_root==1">编辑
                </a-button>
                <a-button type="link" danger @click="deleteItem(record)" v-if="record.is_root!=1">删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>

      </div>
    </div>

    <!--  新增、编辑字段  -->
    <ChannelEditField :id="editId" :village-id="editVillageId" :visible="editVisible"
                      @toClose="editVisible=false"
                      @onSuccess="refreshList"/>

  </a-drawer>


</template>

<script>
import {ref, toRefs, watch, reactive} from "vue";
import ChannelEditField from "./ChannelEditField.vue";
import request from '@/common/utils/request'
import refresh from '@/views/refresh/index.vue'
import {UnorderedListOutlined, HomeOutlined} from "@ant-design/icons-vue";
import utils from '@/common/utils/utils'
import {message} from 'ant-design-vue'


export default {
  computed: {
    refresh() {
      return refresh
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  components: {
    ChannelEditField,
    UnorderedListOutlined,
    HomeOutlined
  },
  setup(props, context) {

    const state = reactive({
      editVisible: false,
      editId: 0,
      editVillageId: 0,
      tableList: [],
      villageList: [],
      selectIndex: -1,
      showPublic: false,
      projectName: "--",//关联项目

    })
    const searchFormRef = ref()
    const modelRef = reactive({
      field_name: "",
    })
    const onClose = () => {
      context.emit("toClose");
    }


    const getTableData = () => {
      const params = {}
      for (let key in modelRef) {
        if (modelRef[key]) {
          params[key] = modelRef[key]
        }
      }
      if (state.selectIndex == -1) {
        //默认项目
        params.is_root = 1
      } else {
        //选择的项目
        const item = state.villageList[state.selectIndex]
        params.village_id = item.value
        params.is_root = state.showPublic ? -1 : 0
      }
      request.get("/org", "/business/clueField/getClueField", params).then(res => {
        console.log(res)
        state.tableList = res.data;
      })
    }

    const addItem = () => {
      state.editId = 0;
      state.editVisible = true;
    }
    const editItem = (item) => {
      state.editId = item.id;
      state.editVisible = true;
    }

    const deleteItem = (item) => {
      utils.modalConfirm({
        content: "确认要删除此自定义字段吗？",
        okType: "danger",
        centered: true,
        onOk: () => {
          // 选择的项目
          const village = state.villageList[state.selectIndex]
          request
              .del("/org", "/business/clueField/delClueField", {
                id: item.id,
                village_id: village.value
              })
              .then((res) => {
                message.success(res.msg || "删除成功");
                getTableData();
              });
        },
      });

    }

    const changePublic = () => {
      state.showPublic = !state.showPublic
      getTableData()
    }

    const reset = () => {
      searchFormRef.value.resetFields()
      getTableData()
    }

    const toSearch = () => {
      getTableData()
    }

    const getVillageList = () => {
      request
          .get("/org", "/build/villageAndBuildList/v2",)
          .then((res) => {
            let vList = [];
            res.villageList.forEach((item) => {
              vList.push({
                label: item.name,
                value: item.id,
              });
            });
            state.villageList = vList;

          });
    };

    const refreshList = () => {
      state.editVisible = false;
      getTableData();
    }

    const init = () => {
      getTableData()
      getVillageList()
    }

    watch(() => props.visible, (value) => {
      if (value) {
        init()
      }
    })

    const changeProject = (index) => {
      state.selectIndex = index;
      if (state.selectIndex == -1) {
        // state.editVillageId = ;
        state.projectName = "--";
      } else {
        const item = state.villageList[index];
        state.editVillageId = item.value;
        state.projectName = item.label;
      }
      getTableData();
    }

    let timer = null
    const changeSort = (record, e) => {

      if (timer) {
        return
      }
      const param = {
        id: record.id,
        sort: e
      }
      request.put("/org", "/business/clueField/editClueField", param).then(res => {

      }).finally(() => {
        timer = setTimeout(() => {
          timer = null
        }, 2000)
      })

    }

    const columns = [
      {title: "字段名称", key: "field_name", dataIndex: "field_name"},
      {title: "字段类型", key: "field_type"},
      {title: "是否必填", key: "is_required"},
      {title: "关联项目", key: "projectName",},
      {title: "排序", key: "sort"},
      {title: "操作", key: "action"}
    ]

    return {
      ...toRefs(state),
      onClose,
      columns,
      addItem,
      editItem,
      deleteItem,
      toSearch,
      reset,
      searchFormRef,
      modelRef,
      refreshList,
      changeProject,
      changeSort,
      changePublic

    }
  }
}
</script>

<style lang="less" scoped>
.box {
  height: 100%;


  .left {
    padding: 10px 16px 10px 0;
    width: 200px;

    .open-config {
      cursor: pointer;
      padding: 5px 10px;
      width: 100%;
    }
  }

  .config {
    flex: 1;
    background-color: rgba(242, 242, 245, 1);
    padding: 10px;
    overflow: scroll;

    .table-config {
      padding: 10px;
      background-color: #fff;
    }


  }


  .select-style {
    background-color: rgba(237, 245, 255, 1);
  }
}

.ant-drawer-body {
  flex-grow: 1 !important;
}

:deep(.ant-list-item) {
  padding: 2px 0;
  border-bottom: 0 solid #f2f3f3;
}

</style>